package com.fqcar.fqdf;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.webkit.WebView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.CannedAccessControlList;
import com.alibaba.sdk.android.oss.model.CreateBucketRequest;
import com.alibaba.sdk.android.oss.model.CreateBucketResult;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.facebook.stetho.Stetho;
import com.fqcar.fqdf.service.LocationService;
import com.fqcar.fqdf.service.VolleySingleton;
import com.fqdf.framework.android.util.AndroidUtils;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import net.danlew.android.joda.JodaTimeAndroid;



/**
 * Created by lvsidong on 16/2/29.
 */
//@Modules({"app"})
public class DFApp extends Application implements BDLocationListener{

    private BDLocation curBDLocation;
    public static LocationService locationService;

//    private AMapLocation curAMAPLocation;

//    private AMapLocationClient mlocationClient;
    private static OSS oss;
    // 运行sample前需要配置以下字段为有效的值
    public static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static final String uploadFilePath = "<upload_file_path>";
    public static final String bucketName = "difu-fanqiecar";
    public static final String OSSBaseUrl = "http://" + bucketName + ".oss-cn-beijing.aliyuncs.com/";
    private static final String uploadObject = "sampleObject";
    private static final String downloadObject = "sampleObject";

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);

    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d("debug flage", String.valueOf(BuildConfig.DEBUG));

        if (BuildConfig.DEBUG) {


            Stetho.initializeWithDefaults(this);

            if (AndroidUtils.isSupportVersion(Build.VERSION_CODES.KITKAT)) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        VolleySingleton.initInstance(this);

        JodaTimeAndroid.init(this);

        initBDMap();
        initBDLocation();
        initOSS();

//        initLocation();

        //二维码扫描初始化
        ZXingLibrary.initDisplayOpinion(this);

    }

    /**
     * 初始化百度地图服务
     */
    private void initBDMap() {
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(this);
        SDKInitializer.setCoordType(CoordType.GCJ02);
    }

    /**
     * 初始化定位服务
     */
    private void initBDLocation() {
        if (locationService != null) {
            stopLocation();
        }
        locationService = new LocationService(this);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.registerListener(this);
        locationService.start();

    }

    /**
     * 初始化定位
     */
    /*public void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(1000);

//        mLocationOption.setGpsFirst(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位参数
        mlocationClient.setLocationListener(this);
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();

    }*/

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    /*public void destroyLocation() {
        if (null != mlocationClient) {
            *//**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             *
             *//*
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
    }*/

    @Override
    public void onTerminate() {
        VolleySingleton.getInstance().stop();
//        destroyLocation();
        stopLocation();
        super.onTerminate();

    }

    public static OSS getOss() {
        return oss;
    }

    /**
     * 关闭定位
     */
    public void stopLocation() {
        if (locationService != null) {
            locationService.unregisterListener(this);
            locationService.stop();
        }
    }

    /**
     * 获取当前定位的location
     *
     * @return
     */
    public BDLocation getCurLocation() {
        return curBDLocation;
    }

    /**
     * 更新当前application中存储的定位信息
     * @param location
     */
    public void setLocation(BDLocation location) {
        curBDLocation = location;
    }

    /**
     * 获取当前定位的location
     *
     * @return
     */
    /*public AMapLocation getCurLocation() {
        return curAMAPLocation;
    }*/

    /**
     * 更新当前application中存储的定位信息
     *
     * @param location
     */
    /*public void setLocation(AMapLocation location) {
        curAMAPLocation = location;
    }*/

    /**
     * 获取城市码
     *
     * @return
     */
    public String getCityCode() {
        // 百度定位
        return curBDLocation == null ? null : curBDLocation.getCityCode();


//        return curAMAPLocation == null ? null : curAMAPLocation.getCityCode();
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {

        if (null != bdLocation && bdLocation.getLocType() != BDLocation.TypeServerError) {
            curBDLocation = bdLocation;
        }
    }

    /*@Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(null != aMapLocation){
            curAMAPLocation = aMapLocation;
        }

    }*/
    private void initOSS() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIJnjQMAeT0gnJ", "Z9tHvWuQTcpaFDADUqinrnExrla89h");
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(5); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        createBucketRequest.setBucketACL(CannedAccessControlList.PublicRead);
        createBucketRequest.setLocationConstraint("oss-cn-shanghai");
        OSSAsyncTask createTask = oss.asyncCreateBucket(createBucketRequest, new OSSCompletedCallback<CreateBucketRequest, CreateBucketResult>() {
            @Override
            public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
                Log.d("locationConstraint", request.getLocationConstraint());
            }

            @Override
            public void onFailure(CreateBucketRequest request, ClientException clientException, ServiceException serviceException) {
                // 请求异常
                if (clientException != null) {
                    // 本地异常如网络异常等
                    clientException.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

}